var myCenter = new google.maps.LatLng(25.759, -80.374);
var map;
var lastOpenedInfoWindow;
var currentMarkerList = [];

function initialize() {
	var mapProp = {
		center : myCenter,
		zoom : 4,
		mapTypeId : google.maps.MapTypeId.ROADMAP
	};

	map = new google.maps.Map(document.getElementById("googleMap"), mapProp);

	// var tweetList = null;
	// addTweetsOnMap(tweetList);
}

/**
 * 
 * @param map
 * @param tweetList
 *            each element in the list is a tweet in JSON format containing the
 *            keys of "content", "lat", and "lng"
 */
function addTweetsOnMap(tweetList) {

	// var testTweet = {"content": "This is content", "lat": 25.759, "lng":
	// -80.374 };
	//	
	// var testMarker = new google.maps.Marker({
	// position : new google.maps.LatLng(testTweet.lat, testTweet.lng),
	// title : 'Click to view details'
	// });
	//
	// testMarker.setMap(map);
	//	
	// addTweetEvent(map, testMarker, testTweet);

	// remove old markers
	$.each(currentMarkerList, function(index, marker) {
		marker.setMap(null);
	});

	currentMarkerList = [];

	if (tweetList == null || tweetList.length == 0)
		return;

	var isFirst = true;
	$.each(tweetList, function(index, tweet) {

		if (tweet.lat != null && tweet.lng != null) {
			if (isFirst == true) {
				map.setCenter(new google.maps.LatLng(tweet.lat, tweet.lng));
				isFirst = false;
			}

			var marker = new google.maps.Marker({
				position : new google.maps.LatLng(tweet.lat, tweet.lng),
				title : "Click to view tween content"
			});
			currentMarkerList.push(marker);
			marker.setMap(map);
			addTweetEvent(map, marker, tweet);
		}

	});
}

function addTweetEvent(map, marker, tweet) {
	if (map == null || marker == null)
		return;

	google.maps.event.addListener(marker, 'click', function() {
		var infoOpts = {
			content : tweet.content,
			boxStyle : {
				background : "none transparent",
				width : "180px"
			},
			pixelOffset : new google.maps.Size(0, 0),
			closeBoxMargin : "5px"
		};

		if (lastOpenedInfoWindow != null) {
			lastOpenedInfoWindow.close();
		}

		lastOpenedInfoWindow = new google.maps.InfoWindow(infoOpts);
		lastOpenedInfoWindow.open(map, marker);
	});
}

function addRandomLatLng(tweetList) {
	var modifiedTweetList = [];
	$.each(tweetList, function(index, entry) {
		var modifiedTweet = entry;
		modifiedTweet.lat = Math.random() * 360 - 180;
		modifiedTweet.lng = Math.random() * 360 - 180;
		modifiedTweetList.append(modifiedTweet);
	});
	return modifiedTweetList;

}
